package elion.com.theElion.fragmentLandData;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import elion.com.elion.R;
import elion.com.theElion.activityMain.LandActivity;
import elion.com.theElion.util.Info;
import elion.com.theElion.util.UIHelper;
import elion.com.theElion.util.adapter.LandSelectFragmentAdapter;
import elion.vo.Land;

import static elion.com.theElion.util.HttpUtils.sendPostMethod;

/**
 * A fragment representing a list of Items.
 * <p/>
 * interface.
 */
public class LandSelectFragment extends Fragment
{

    private RecyclerView recyclerView;

    private static final String ARG_COLUMN_COUNT = "column-count";
    private static final String SELECTED_DESERT_ID = "selected_desert_id";

    private int mColumnCount = 1;
    private String mSelectedDesertId;
    private LandSelectFragmentAdapter.OnItemClickLitener mItemClickListener;
    private View view;
    private List<Land> myLands;
    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */

    public LandSelectFragment()
    {

    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static LandSelectFragment newInstance(int columnCount, String desertId)
    {

        LandSelectFragment fragment = new LandSelectFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        args.putString(SELECTED_DESERT_ID, desertId);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        if (getArguments() != null)
        {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
            mSelectedDesertId = getArguments().getString(SELECTED_DESERT_ID);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.fragment_land_select_item_list, container, false);

        // Set the adapter
        if (view instanceof LinearLayout)
        {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view.findViewById(R.id.list_land_select);

            if (mColumnCount <= 1)
            {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
                new QueryLandAsyncTask().execute(Info.path_SelectLand(mSelectedDesertId));

//这句话应该在异步里

            }
            else
            {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
        }
        return view;
    }


    @Override
    public void onAttach(Context context)
    {
        super.onAttach(context);
    }

    @Override
    public void onDetach()
    {
        super.onDetach();
    }


    class QueryLandAsyncTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... strings)
        {
            System.out.println(strings[0]+"异步加载");
            return sendPostMethod(strings[0], "utf-8");
        }
        @Override
        protected void onPostExecute(String result)
        {

            super.onPostExecute(result);
            if (result==null||result.equals(""))
            {
                Log.w("ContentFragment","进入result查询失败分支");
                //当没有数据时，添加10条假数据
                myLands = new ArrayList<>();
                for (int i = 0; i < 10 ; i++)
                {
                    myLands.add(new Land("无数据","000"));
                }
            }
            else
            {
                Log.i("ContentFragment","进入result不为空分支");
                //JSON解析
                myLands = JSONMyLandData(result);

            }
            mItemClickListener = new LandSelectFragmentAdapter.OnItemClickLitener()
            {

                @Override
                public void onItemClick(View view, int position)
                {
                    Intent intent =new Intent(getActivity(), LandActivity.class);
                    intent.putExtra("landId",view.getTag(R.id.landId)+"");
                    intent.putExtra("landName",view.getTag(R.id.landName)+"");
                    startActivity(intent);

                }

                @Override
                public void onItemLongClick(View view, int position)
                {

                }
            };
            recyclerView.setAdapter(new LandSelectFragmentAdapter(myLands, mItemClickListener));
            new UIHelper().hideDialogForLoading();
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            new UIHelper().showDialogForLoading(getActivity(), "正在加载...", true);
        }
    }
    private List<Land> JSONMyLandData(String result)
    {
        List<Land> myLands=new ArrayList<>();
        try {
            JSONArray array = new JSONArray(result);
            JSONObject jsonObject;
            Log.i("LandSelectFragment","array.length"+array.length());
            for (int i = 0; i < array.length(); i++)
            {
                jsonObject = array.getJSONObject(i);
                Land land = new Land
                        (jsonObject.getString("name"),jsonObject.getString("number")
                        );
                System.out.println("land json解析"+land.getLandId()+land.getLandName());
                myLands.add(land);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return myLands;
    }
}
